package com.shaoshaohuo.app.utils;

import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.ParseException;

/**
 * @author osborn 数字相关帮忙类
 */
public class NumberUtil {
	public static final int FORMAT_MONEY_CEIL = 1;//非0进位。如2.002，换算为2.01
	public static final int FORMAT_MONEY_ROUND = 2;//四舍五入。如2.004，换算为2.00；2.006，换算为2.01
	public static final int FORMAT_MONEY_FLOOR = 3;//非0舍弃。如2.003，换算为2.00
	
	public static final int FRACTION_DIGIT_MONEY = 2;//金额的小数最大位数
	/**
	 * 解析字符串为数字
	 * @param num	被解析为double的字符串
	 * @param defNum	默认值
	 * @return
	 */
	public static double parse(String num, double defNum) {
		try {
			return Double.parseDouble(num);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return defNum;
	}

	/**
	 * 见double parse(String num, double defNum), defNum = 0
	 * @param num
	 * @return
	 */
	public static double parse(String num) {
		return parse(num, 0);
	}
	
	/**
	 * 处理金额数字，最大两位小数
	 * @param money
	 * @param moneyFormat	三种，FORMAT_MONEY_CEIL，FORMAT_MONEY_ROUND，FORMAT_MONEY_FLOOR，分别表示“非0进位”、“四舍五入”、“非0舍弃”
	 * @return
	 */
	public static synchronized double formatMoney(double money, int moneyFormat) {
		NumberFormat format = NumberFormat.getNumberInstance();
		format.setGroupingUsed(false);
		format.setMaximumFractionDigits(FRACTION_DIGIT_MONEY);
		switch(moneyFormat) {
		case FORMAT_MONEY_CEIL:
			format.setRoundingMode(RoundingMode.CEILING);
			return Double.parseDouble(format.format(money)); 
		case FORMAT_MONEY_ROUND:
			format.setRoundingMode(RoundingMode.HALF_UP);
			return Double.parseDouble(format.format(money)); 
		case FORMAT_MONEY_FLOOR:
			format.setRoundingMode(RoundingMode.FLOOR);
			return Double.parseDouble(format.format(money)); 
		default:
			return money;
		}
	}
	
	/**
	 * 解析金额字符串，小数后可以带2位
	 * @param number
	 * @return
	 * @throws java.text.ParseException	不符合格式的，抛出异常
	 */
	public static double parseMoneyNumber(String number) throws ParseException {
		NumberFormat format = NumberFormat.getNumberInstance();
		format.setGroupingUsed(false);
		format.setMaximumFractionDigits(FRACTION_DIGIT_MONEY);
		return format.parse(number.trim()).doubleValue();
	}
	
	public static void main(String[] args) {
		double a = 2.004;
		System.out.println(formatMoney(a, FORMAT_MONEY_CEIL));
		System.out.println(formatMoney(a, FORMAT_MONEY_ROUND));
		System.out.println(formatMoney(a, FORMAT_MONEY_FLOOR));
		a = 2.005;
		System.out.println(formatMoney(a, FORMAT_MONEY_CEIL));
		System.out.println(formatMoney(a, FORMAT_MONEY_ROUND));
		System.out.println(formatMoney(a, FORMAT_MONEY_FLOOR));
		
	}
}
